import React, { useState, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { HVACDevice } from '../../../types';

interface HVACDeviceProps {
  device: HVACDevice;
  isSelected?: boolean;
  onClick?: () => void;
}

const HVACDeviceComponent: React.FC<HVACDeviceProps> = ({
  device,
  isSelected = false,
  onClick
}) => {
  const groupRef = useRef<THREE.Group>(null);
  const fanRef = useRef<THREE.Mesh>(null);
  const [isHovered, setIsHovered] = useState(false);
  const [fanRotation, setFanRotation] = useState(0);

  // 根据设备类型获取颜色
  const getDeviceColor = (): string => {
    switch (device.type) {
      case 'AC':
        return '#03A9F4'; // 亮蓝色
      case 'Heater':
        return '#FF5722'; // 橙色
      case 'Fan':
        return '#795548'; // 棕色
      case 'Ventilation':
        return '#4CAF50'; // 绿色
      default:
        return '#607D8B'; // 蓝灰色
    }
  };

  // 根据设备状态获取颜色
  const getStatusColor = (): string => {
    switch (device.status) {
      case 'online':
        return '#4CAF50';
      case 'offline':
        return '#9E9E9E';
      case 'warning':
        return '#FFC107';
      case 'error':
        return '#F44336';
      default:
        return '#2196F3';
    }
  };



  // 处理点击事件
  const handleClick = (event: React.MouseEvent) => {
    event.stopPropagation();
    if (onClick) {
      onClick();
    }
  };

  // 处理鼠标悬停事件
  const handleMouseEnter = () => {
    setIsHovered(true);
  };

  const handleMouseLeave = () => {
    setIsHovered(false);
  };

  // 风扇旋转动画
  useFrame(() => {
    if (device.status === 'online' && fanRef.current) {
      const speedFactor = device.fanSpeed / 100; // 假设fanSpeed是0-100的百分比
      setFanRotation(prevRotation => prevRotation + (0.05 * speedFactor));
      
      if (fanRef.current) {
        fanRef.current.rotation.z = fanRotation;
      }
    }
  });

  // 根据设备类型创建不同的模型
  const renderDeviceModel = () => {
    const color = getDeviceColor();
    const hasFan = device.type === 'AC' || device.type === 'Fan' || device.type === 'Ventilation';
    
    switch (device.type) {
      case 'AC':
        // 空调模型 - 矩形箱体带出风口
        return (
          <group>
            <mesh position={[0, 0.5, 0]}>
              <boxGeometry args={[1.2, 0.6, 0.4]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
            </mesh>
            
            {/* 出风口 */}
            <mesh position={[0, 0.5, 0.21]}>
              <boxGeometry args={[1, 0.4, 0.05]} />
              <meshStandardMaterial color="#BDBDBD" roughness={0.7} metalness={0.2} />
            </mesh>
            
            {/* 控制面板 */}
            <mesh position={[0, 0.8, 0]} rotation={[Math.PI / 2, 0, 0]}>
              <planeGeometry args={[0.8, 0.3]} />
              <meshStandardMaterial color="#F5F5F5" roughness={0.5} metalness={0.1} />
            </mesh>
            
            {/* 风扇（内部） */}
            {hasFan && device.status === 'online' && (
              <mesh
                ref={fanRef}
                position={[0, 0.5, 0]}
              >
                <circleGeometry args={[0.3, 4]} />
                <meshStandardMaterial color="#212121" roughness={0.6} metalness={0.4} />
              </mesh>
            )}
          </group>
        );
        
      case 'Heater':
        // 加热器模型 - 方形带散热片
        return (
          <group>
            <mesh position={[0, 0.4, 0]}>
              <boxGeometry args={[0.8, 0.4, 0.4]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
            </mesh>
            
            {/* 散热片 */}
            <group position={[0, 0.4, 0.21]}>
              {Array.from({ length: 5 }).map((_, index) => (
                <mesh
                  key={`fin-${index}`}
                  position={[0, 0.4 - (index - 2) * 0.1, 0]}
                >
                  <boxGeometry args={[0.7, 0.05, 0.03]} />
                  <meshStandardMaterial color="#FF9800" roughness={0.7} metalness={0.4} />
                </mesh>
              ))}
            </group>
            
            {/* 控制旋钮 */}
            <mesh position={[0.5, 0.4, 0]}>
              <cylinderGeometry args={[0.08, 0.08, 0.05, 8]} />
              <meshStandardMaterial color="#795548" roughness={0.7} metalness={0.5} />
            </mesh>
          </group>
        );
        
      case 'Fan':
        // 风扇模型 - 圆形带叶片
        return (
          <group>
            <mesh position={[0, 0.3, 0]}>
              <cylinderGeometry args={[0.4, 0.4, 0.1, 12]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
            </mesh>
            
            {/* 风扇叶片 */}
            {hasFan && (
              <mesh
                ref={fanRef}
                position={[0, 0.3, 0]}
              >
                <circleGeometry args={[0.5, 3]} />
                <meshStandardMaterial color="#212121" roughness={0.6} metalness={0.4} />
              </mesh>
            )}
            
            {/* 支架 */}
            <mesh position={[0, 0, 0]}>
              <cylinderGeometry args={[0.1, 0.1, 0.6, 8]} />
              <meshStandardMaterial color="#616161" roughness={0.7} metalness={0.4} />
            </mesh>
          </group>
        );
        
      case 'Ventilation':
        // 通风设备模型 - 管道式
        return (
          <group>
            <mesh position={[0, 0.4, 0]}>
              <cylinderGeometry args={[0.3, 0.3, 0.8, 12]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
            </mesh>
            
            {/* 通风口 */}
            <mesh position={[-0.4, 0.4, 0]}>
              <circleGeometry args={[0.25, 8]} />
              <meshStandardMaterial color="#424242" roughness={0.7} metalness={0.4} />
            </mesh>
            <mesh position={[0.4, 0.4, 0]}>
              <circleGeometry args={[0.25, 8]} />
              <meshStandardMaterial color="#424242" roughness={0.7} metalness={0.4} />
            </mesh>
            
            {/* 内部风扇 */}
            {hasFan && device.status === 'online' && (
              <mesh
                ref={fanRef}
                position={[0, 0.4, 0]}
              >
                <circleGeometry args={[0.2, 4]} />
                <meshStandardMaterial color="#212121" roughness={0.6} metalness={0.4} />
              </mesh>
            )}
          </group>
        );
        
      default:
        // 默认模型
        return (
          <mesh position={[0, 0.5, 0]}>
            <boxGeometry args={[1, 0.5, 0.4]} />
            <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
          </mesh>
        );
    }
  };

  // 为空调和加热器添加温度指示效果
  const renderTemperatureEffect = () => {
    if (device.type === 'AC' && device.status === 'online') {
      // 冷气效果
      return (
        <mesh position={[0, 0.3, 0.4]}>
          <boxGeometry args={[0.8, 0.3, 0.2]} />
          <meshStandardMaterial 
            color="#03A9F4" 
            transparent={true}
            opacity={0.5} 
            roughness={0.2} 
            metalness={0.1}
          />
        </mesh>
      );
    }
    if (device.type === 'Heater' && device.status === 'online') {
      // 热气效果
      return (
        <mesh position={[0, 0.3, 0.4]}>
          <boxGeometry args={[0.8, 0.3, 0.2]} />
          <meshStandardMaterial 
            color="#FF5722" 
            transparent={true}
            opacity={0.5} 
            roughness={0.2} 
            metalness={0.1}
          />
        </mesh>
      );
    }
    return null;
  };

  return (
    <group
      ref={groupRef}
      position={[device.position.x, device.position.y, device.position.z]}
      onClick={handleClick}
      onPointerEnter={handleMouseEnter}
      onPointerLeave={handleMouseLeave}
    >
      {/* 设备主体 */}
      {renderDeviceModel()}
      
      {/* 温度效果（如果适用） */}
      {renderTemperatureEffect()}
      
      {/* 状态指示器 */}
      <mesh
        position={[0, 0.9, 0]}
      >
        <sphereGeometry args={[0.08]} />
        <meshStandardMaterial
          color={getStatusColor()}
          emissive={getStatusColor()}
          emissiveIntensity={0.6}
          roughness={0.2}
          metalness={0.3}
        />
      </mesh>
      
      {/* 选中边框 */}
      {isSelected && (
        <lineSegments>
          <edgesGeometry
            args={[
              new THREE.BoxGeometry(1.5, 1.5, 1)
            ]}
          />
          <lineBasicMaterial
            color="#2196F3"
            linewidth={3}
          />
        </lineSegments>
      )}
      
      {/* 悬停效果 */}
      {isHovered && (
        <lineSegments>
          <edgesGeometry
            args={[
              new THREE.BoxGeometry(1.4, 1.4, 0.9)
            ]}
          />
          <lineBasicMaterial
            color="#64B5F6"
            linewidth={2}
          />
        </lineSegments>
      )}
    </group>
  );
};

export default React.memo(HVACDeviceComponent);